package com.example.auth.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.example.auth.model.entity.OAuthClient;
import com.example.auth.service.OAuthClientService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.Resource;

/**
 * Sa-Token 配置类
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Resource
    private OAuthClientService clientService;

    /**
     * 注册Sa-Token拦截器，进行权限认证
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 登录校验 - 拦截所有规则，排除登录接口和OAuth2接口
            SaRouter.match("/**")
                    .notMatch(
                            // 认证相关接口
                            "/login/**",
                            "/auth/login",
                            "/auth/register",

                            // OAuth2相关接口和资源
                            "/oauth2/**",
                            "/oauth2/login",
                            "/oauth2/doLogin",
                            "/oauth2/authorize",
                            "/oauth2/confirm",
                            "/oauth2/doConfirm",
                            "/oauth2/token",
                            "/oauth2/userinfo",
                            "/oauth2/error",

                            // 错误页面
                            "/error",

                            // Swagger相关资源
                            "/swagger-ui/**",
                            "/v3/api-docs/**",
                            "/swagger-resources/**",
                            "/doc.html",

                            // Knife4j相关资源
                            "/webjars/**",
                            "/favicon.ico"

                    )
                    .check(r -> StpUtil.checkLogin());

            // 权限认证 - 不同角色访问不同接口
            SaRouter.match("/admin/**", r -> StpUtil.checkRole("ADMIN"));
            SaRouter.match("/manager/**", r -> StpUtil.checkRoleOr("ADMIN", "MANAGER"));
            SaRouter.match("/employee/**", r -> StpUtil.checkRoleOr("ADMIN", "MANAGER", "EMPLOYEE"));

            // OAuth2客户端管理接口，仅管理员可访问
            SaRouter.match("/oauth/client/**", r -> StpUtil.checkRole("ADMIN"));

            // 特定接口的权限验证
            SaRouter.match("/user/update", r -> StpUtil.checkPermission("user:update"));
            SaRouter.match("/user/delete", r -> StpUtil.checkPermission("user:delete"));
        })).addPathPatterns("/**");
    }
} 